import 'dart:collection';

import 'package:ac/api/ac_urls.dart';
import 'package:ac/common/style.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/page/ac_me/ac_me_logic.dart';
import 'package:ac/route/ac_route_pages.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

mixin AcGiftMixin<T extends StatefulWidget> on State<T> {
  OverlayEntry? _overlayEntry;
  final Queue<int?> _svgaUrlQueue = Queue();
  bool _allowShow = true;

  set allowShow(bool value) {
    _allowShow = value;
  }

  /// 弹出送礼弹窗
  showRewardDialog() {
    Get.dialog(StatefulBuilder(builder: (context, setState) {
      return SizedBox(
        width: 375.w,
        height: 812.h,
        child: Column(
          children: [
            Expanded(
              child: Container(
                color: Colors.black.withOpacity(0.5),
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Get.back();
                  },
                  child: Container(),
                ),
              ),
            ),
            Container(
              width: 375.w,
              height: 248.h,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10.r),
              ),
              padding: EdgeInsets.all(20.w),
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        height: 28.h,
                        padding: EdgeInsets.symmetric(horizontal: 10.w),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(22.w),
                          gradient: const LinearGradient(
                            colors: [
                              Color(0xFFFFC371),
                              Color(0xFFFF5F6D),
                            ],
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(
                              "images/icon_coin.png",
                              width: 21.w,
                            ),
                            SizedBox(width: 6.w),
                            Text(
                              "${AcUserManager.userInfoModel?.userInfo.availableCoins}",
                              style: TextStyle(
                                  fontSize: 16.sp, color: Colors.white),
                            )
                          ],
                        ),
                      ),
                      const Spacer(),
                      GestureDetector(
                        onTap: () {
                          Get.back();
                          Get.toNamed(AcRouteNames.goodsPage);
                        },
                        child: Container(
                          height: 26.h,
                          padding: EdgeInsets.symmetric(horizontal: 10.w),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(22.w),
                            gradient: const LinearGradient(
                              colors: [
                                Color(0xFFFFC371),
                                Color(0xFFFF5F6D),
                              ],
                            ),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            "Get coins",
                            style:
                                TextStyle(fontSize: 16.sp, color: Colors.white),
                          ),
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 33.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _giftItem(1, 39, setState),
                      _giftItem(2, 69, setState),
                      _giftItem(3, 99, setState),
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      );
    }), useSafeArea: false);
  }

  Widget _giftItem(
    int index,
    int price,
    StateSetter setState,
  ) {
    return GestureDetector(
      onTap: () {
        consumeGift(index, price, setState);
      },
      child: Column(
        children: [
          Image.asset(
            "images/icon_gitf$index.png",
            width: 86.w,
          ),
          SizedBox(height: 17.h),
          Row(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                "images/icon_coin.png",
                width: 21.w,
              ),
              SizedBox(width: 6.w),
              Padding(
                padding: EdgeInsets.only(top: 2.h),
                child: Text(
                  "$price",
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: textColorBlack,
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  Future<void> consumeGift(
    int index,
    int price,
    StateSetter setState,
  ) async {
    if ((AcUserManager.userInfoModel!.userInfo.availableCoins ?? 0) < price) {
      Get.back();
      Get.toNamed(AcRouteNames.goodsPage);
      return;
    }
    var res = await AcUrls.consume.post(
      data: {"outlay": price, "source": "iap"},
      showLoading: true,
    );
    if (res?["code"] == 0) {
      await AcUserManager.updateUserInfoFromRemote();
      Get.find<AcMeLogic>().userInfo.value =
          AcUserManager.userInfoModel?.userInfo;
      setState(() {});
      Get.back();
      playSvga(index);
    }
  }

  /// 显示礼物svga动画
  playSvga(int index) {
    if (!_allowShow) return;
    _svgaUrlQueue.add(index);
    _showSvga();
  }

  void _showSvga() {
    if (_overlayEntry != null) {
      return;
    }
    if (_svgaUrlQueue.isNotEmpty) {
      var url = _svgaUrlQueue.removeFirst();
      _overlayEntry = OverlayEntry(
        builder: (context) {
          return RewardResultWidget(
            index: url!,
            animatedCompleteBlock: () {
              _overlayEntry?.remove();
              _overlayEntry = null;
              _showSvga();
            },
          );
        },
      );
      if (mounted) Overlay.of(context).insert(_overlayEntry!);
    }
  }

  /// 清除动画 正常用去跳转其他页面时移除当前动画
  void cleanGiftAnimation() {
    _overlayEntry?.remove();
    _overlayEntry = null;
    _svgaUrlQueue.clear();
  }

  @override
  void initState() {
    super.initState();
    _allowShow = true;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _allowShow = false;
    _overlayEntry?.remove();
  }
}

class RewardResultWidget extends StatefulWidget {
  final int index;

  final VoidCallback animatedCompleteBlock;

  const RewardResultWidget({
    super.key,
    required this.index,
    required this.animatedCompleteBlock,
  });

  @override
  State<RewardResultWidget> createState() => _RewardResultWidgetState();
}

class _RewardResultWidgetState extends State<RewardResultWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late CurvedAnimation _curvedAnimation;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _animationController = AnimationController(
        duration: const Duration(milliseconds: 500), vsync: this);
    _animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        Future.delayed(const Duration(milliseconds: 2000), () {
          _animationController.reverse();
        });
      }
      if (status == AnimationStatus.dismissed) {
        widget.animatedCompleteBlock();
      }
    });
    _curvedAnimation =
        CurvedAnimation(parent: _animationController, curve: Curves.easeInOut);
    _animationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 100.h),
      height: 812.h,
      alignment: Alignment.topCenter,
      child: ScaleTransition(
        scale: _curvedAnimation,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Image.asset(
              "images/gift_bg.png",
              width: 375.w,
            ),
            Image.asset(
              "images/icon_gitf${widget.index}.png",
              width: 261.w,
            ),
          ],
        ),
      ),
    );
  }
}
